<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-8-25
 * Time: 10:12
 */

namespace common\components\services\message;

use common\components\helpers\EventData;
use common\components\helpers\Fun;
use common\models\datas\MessageLog;
use yii\base\BaseObject;

class SmsMessage extends BaseObject
{
    public function send($id,$site_id=null){
        sleep(1);
        $item=MessageLog::findOne([$id]);
        $failed_array=[];
        if ($item !=null && $item->receiver_arr!=null) {
            $receive_array=unserialize($item->receiver_arr);
            $send_group_array=(new EventData())->getSendGroupArrayByKey($item->send_group);
            if($send_group_array!=null && $send_group_array['model']!=null){
                $model_class=$send_group_array['model'];
                $receive_array=array_filter($model_class::find()->select(['mobile'])->where(['id'=>$receive_array])->asArray()->column());
            }
            if(count($receive_array)>0){
                foreach($receive_array as $k=>$v){
                    $data=['mobile'=>$v,'content'=>$item->content_sms];
                    $status=\Yii::$app->smsSend->send($data);
                    if($status['code']!=2){
                        $failed_array[]=$v;
                    }
                }
            }else{
                $failed_array=unserialize($item->receiver_arr);
            }
            if(count($failed_array)>0){
                $fail_arr=serialize($failed_array);
                $item->fail_arr_sms=$fail_arr;
                $item->save(false);
                return false;
            }else{
                $log_status=unserialize($item->status);
                $log_status['sms']=1;
                $item->status = serialize($log_status);
                $item->save(false);
                return true;
            }
        }
        return false;
    }
}